<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop:'timeOfEntry',order:'ascending'}">
          <el-table-column label="序号" type="index" width="100" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" style="width:100px;height:100px">
            </template>
          </el-table-column>

          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工的弹窗 -->
      <el-dialog
        title="新增"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <empDialogfrom
          ref="empDialog"
          @close="showDialog=false"
          @success="hSuccess"
        />

      </el-dialog>
      <!-- 给员工分配角色的弹窗
       -->
      <el-dialog title="分配角色" :visible.sync="RoleShowDialog">
        <assignRole v-if="RoleShowDialog" :role-id="roleId" @close="RoleShowDialog = false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import EmployeeEnum from '@/constant/employees'
import { getEmployees, delEmployee } from '@/api/employees'
import empDialogfrom from './empDialog'
import assignRole from './assignRole.vue'
// console.log(EmployeeEnum.hireType)
const hireType = {}
EmployeeEnum.hireType.forEach(item => { hireType[item.id] = item.value })
// const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
//   acc[item.id] = item.value
//   return acc
// }, {})
// console.log(hireType)
export default {
  components: {
    empDialogfrom, assignRole
  },
  data() {
    return {
      roleId: '', // 存放分配角色的id
      RoleShowDialog: false, // 用来控制角色分配的显示与隐藏
      showDialog: false, // 用来控制弹框的显示与隐藏
      list: [], // 用来保存员工的列表数据
      page: 1, // 页码值
      size: 2, // 每页显示的条数
      total: 0 // 获取的员工列表总数
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // 分配角色的函数
    hAssignRole(id) {
      this.roleId = id
      this.RoleShowDialog = true
    },
    Dateformat(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const one = list[0]
      let headers = []
      if (one) {
        console.log(' Object.keys(one)', Object.keys(one))
        headers = Object.keys(one).map(item => {
          return mapInfo[item]
        })
      }
      const data = list.map(item => {
        return Object.values(item)
      })
      return { headers, data }
    },

    // Excel导出
    async handleDownload() {
      // 1.发送请求获取数据
      try {
        const res = await getEmployees(this.page, this.size)
        // console.log(res)
        if (res.code !== 10000) return
        // 2.需要将获取到的数据进行数据转换为Excel需要格式, header.data
        console.log(res.data.rows)
        const { headers, data } = this.Dateformat(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
        // 3.调用excel.export_json_to_excel将格式好的数据写入Excel文件中
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 删除内容
    hDel(id) {
      this.$confirm('您确定要删除此内容吗').then(async() => {
        const res = await delEmployee(id)
        console.log(res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployees()
      }).catch(err => err)
    },
    // 重置表单
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    hSuccess() {
      // 页面添加完成之后,需要将页码跳到最后
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    // 新增员工
    hAdd() {
      this.showDialog = true
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 封装一个将聘用形式1,2的数据,转换为正式与非正式
    formatEmployment(data) {
      // 如果数据返回的是1,2,则找到跟导入的插件1,2,,相同的键,对象,找到该数据,然后再取里面的value值
      // return EmployeeEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 获取员工的列表数据
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size)
        // console.log(res)
        if (res.code === 10000) {
          this.list = res.data.rows
          this.total = res.data.total
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
